package com.ahaoyou.thread;

/**
 * @author LH
 * @version 1.0
 * @date 2022/9/18 21:55
 */
public class VisiblityTest {
    public static void main(String[] args) throws InterruptedException {
        Visiblity visiblity = new Visiblity();
        new Thread(() -> visiblity.add(), "A").start();
        Thread.sleep(3000);
        new Thread(() -> visiblity.refresh(), "B").start();
        double t = 60 * 0.1;
        System.out.println(t);
    }

    static class Visiblity {

        //private volatile  boolean flag = true;
        private boolean flag = true;

        //private volatile int count = 0;
        private int count = 0;

        public void refresh() {
            flag = false;
            System.out.println(Thread.currentThread().getName() + "開始執行refresh--->" + flag);
        }

        public void add() {
            System.out.println(Thread.currentThread().getName() + "開始執行add");
            while (flag) {
                count++;
                //内存屏障
//                com.ahaoyou.UnsafeFactory.getUnsafe().storeFence();
                // 也可以跳出
                // Thread.yield();
                //也可以跳出
                // System.out.println(count);
//           todo  LockSupport.unpark(Thread.currentThread());
                try {
                    Thread.sleep(100);   //内存屏障
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "結束執行add--->" + count);
        }

    }
}
